package com.sx.service.impl;

import com.sx.domain.Course;
import com.sx.domain.CourseVo;
import com.sx.domain.Teacher;
import com.sx.dao.CourseMapper;
import com.sx.service.CourseService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;


@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> findCourseByCondition(CourseVo courseVo) {
        List<Course> list = courseMapper.findCourseByCondition(courseVo);
        return list;
    }

    @Override
    public void saveCourseOrTeacher(CourseVo courseVo) {
        //封装课程信息
        Course course = new Course();
        Date date = new Date();
        try {
            //补全课程信息
            BeanUtils.copyProperties(course, courseVo);
            course.setCreateTime(date);
            course.setUpdateTime(date);
            courseMapper.saveCourse(course);
            //获取新插入的id值
            int id = course.getId();
            //封装讲师信息
            Teacher teacher = new Teacher();
            BeanUtils.copyProperties(teacher, courseVo);
            teacher.setCourseId(id);
            teacher.setCreateTime(date);
            teacher.setUpdateTime(date);
            teacher.setIsDel(0);
            //保存讲师信息
            courseMapper.saveteacher(teacher);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public CourseVo findCourseById(Integer id) {
        CourseVo courseById = courseMapper.findCourseById(id);
        return courseById;
    }

    @Override
    public void updateCourseOrTeacher(CourseVo courseVo) {
        //封装课程信息
        Course course = new Course();
        //补全信息
        Date date = new Date();

        //封装讲师信息
        Teacher teacher = new Teacher();
        try {
            BeanUtils.copyProperties(course, courseVo);
            course.setUpdateTime(date);
            courseMapper.updateCourse(course);
            BeanUtils.copyProperties(teacher, courseVo);
            teacher.setUpdateTime(date);
            teacher.setCourseId(course.getId());
            courseMapper.updateTeacher(teacher);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateCourseStatus(int id, int status) {
        Course course = new Course();
        course.setId(id);
        course.setStatus(status);
        // 添加日志输出，确认传入的参数值
        System.out.println("Updating course id: " + id + " with status: " + status);
        // 不手动设置updateTime，让数据库通过NOW()函数处理
        courseMapper.updateCourseStatus(course);
    }


}